<template>
<div class="main-container" id="app">
    <div id="mapDiv" class="map-div">
    </div>
    <div class="left-tree" style="margin-top: 10px;margin-left: 10px;">
        <ul id="treeDemo" class="ztree"></ul>
    </div>
</div>
</template>
<script>
import {loadScript, loadCss,loadModules} from 'esri-loader';
import website from '@/config/website';
import {getDeptTreeNode} from "@/api/xapply/gis/gridShow";
import $ from "@/assets/jquery-vendor.js";
import {getNextLevelGridServerNameByDeptCode,
        getAppendParamByDeptCode,
        getGridServerNameByDeptCode,
        getGridLevelByDeptCode
        } from "@/assets/js/gis/util.js";
import "@/assets/js/gis/jquery.ztree.core.js";
import "@/assets/js/gis/jquery.ztree.excheck.min.js";
import "@/assets/css/gis/default.css";
import "@/assets/css/gis/zTreeStyle/zTreeStyle.css";

//var map,gridGraphicsLayer,gridFillSymbol,countyGridArray;
//var zTreeObj; //zTree实例
var 
    //zTreeObj, //zTree实例
    map, //地图实例
    gridGraphicsLayer, //地图网格范围图层
    //textGraphicsLayer, //网格名称标注图层
    gridFillSymbol, //地图网格填充符号
    // pickedGridLayer, //选中网格图层
    // gridWorkerLayer, //网格员图层
    // cameraLayer, //视频监控图层
    // trailLayer, //网格员轨迹实时位置图层
    // trailShowLayer, //网格员轨迹展示图层
    // locationLayer, //网格员分布图层
    // focusPeopleLayer, //重点人员图层
    currentGridPolygon, //当前选中网格范围
    countyGridArray; //区县网格范围集合
    
export default {
  name: 'web-map',
  data() {
      return{
        config: {
                cameraServerUrl: 'GIS_CAMERA',
                baseGridServerUrl: 'GIS_GRID',
                topDeptCode: '',
                topGridId: ''
            },
          commonData: {
              moduleOpenStatue: {

              },
              moduleStatue: {
                  leader: true,
                  worker: false
              },
              gridCode: ''
          },
      }
  },
    created() {
      this.init();
    },
    methods: {
      //加载左侧树
        init(){
              var setting = {data: {simpleData: {enable: true}}, callback: {onClick: this.treeClick}};
              getDeptTreeNode().then(res => {
                const result = res.data;
                $.fn.zTree.init($("#treeDemo"), setting, result.treeNodes);
                  this.config.topDeptCode = result.deptCode;
                  this.config.topGridId = result.gridId;
                  this.commonData.gridCode = result.deptCode;
                  this.initMap();
            })
        },
        //树点击
        treeClick(event, treeId, treeNode) {
            console.log(treeNode);
            if (treeNode.pId == '0' || treeNode.pId == null) {
                console.log("进入111="+this.config.topDeptCode);
                this.commonData.gridCode = this.config.topDeptCode;
            }
            else {  
                console.log("进入222="+treeNode.deptCode);
                this.commonData.gridCode = treeNode.deptCode;
            }
            this.getGridAreaAndData();
        },
        //初始化地图
        initMap(){
            console.log("----");
          loadScript({ url: website.InitUrl})
          loadCss(website.CssUrl)
          loadModules([
                      'esri/map',
                      'esri/layers/ArcGISTiledMapServiceLayer',
                      'esri/layers/GraphicsLayer',
                      'esri/geometry/Polygon',
                      'esri/symbols/SimpleFillSymbol',
                      'esri/symbols/SimpleLineSymbol',
                      'esri/graphic',
                      'esri/Color',
                      'esri/graphicsUtils',
                      'dijit/dijit',
                      'esri/lang',
                      'dojo/dom-style',
                      //'esri/symbols/Font',
                      //'esri/symbols/TextSymbol',
                      //'esri/SpatialReference',
                      //'esri/geometry/Point',
                      'dojo/domReady!',
                  ], { css: true })
                  .then(([
                      Map,
                      ArcGISTiledMapServiceLayer,GraphicsLayer,Polygon,SimpleFillSymbol,SimpleLineSymbol,Graphic,Color,graphicsUtils,dijit,lang,domStyle
                  ]) => {
                      //实例化地图
                      map = new Map("mapDiv", {
                      center: website.MapCenterPoint,
                      zoom: 13,
                      slider: false, //缩放按钮移除
                      logo: false, //logo移除
                      isDoubleClickZoom: false,
                      });
                      let _this = this ;
                      //加载图层
                      let mapServer = new ArcGISTiledMapServiceLayer(website.BaseMapUrl)
                      map.addLayer(mapServer)
                      //地图网格填充符号
                      gridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
                          new Color([66, 0, 0]), 1), new Color([255, 99, 33, 0.15]));
                      //地图网格范围层
                      gridGraphicsLayer = new GraphicsLayer({id: "gridGraphicsLayer"});
                      map.addLayer(gridGraphicsLayer);
                      //tanceng
                      var content =  "<b>${xzqhmc}</b>";
                      gridGraphicsLayer.on("mouse-over", function (evt) {
                          showTooltip(evt, content);
                      });
                      gridGraphicsLayer.on("mouse-out", function () {
                          closeDialog();
                      });
                      function showTooltip(evt, cont, id){
                          console.log("鼠标事件");
                        if(!evt.graphic) return;
                        if(!id) id = "tooltipDialog";
                        closeDialog(id);
                        if(id == "tooltipDialog" ){
                            map.setMapCursor("pointer");
                        }
                        var dialog = new dijit.TooltipDialog({
                            id : id,
                            style : "position: absolute;padding:0px;margin:0;background-color:#fff;font: normal normal normal 13pt Helvetica;z-index:10000;color:black;width:200px;height:auto"
                        });
                        var content = lang.substitute(evt.graphic.attributes, cont);
                        dialog.setContent(content);
                        domStyle.set(dialog.domNode, "opacity", 1);
                        dijit.placeOnScreen(dialog.domNode, {x: evt.pageX, y: evt.pageY}, ["TL", "BL"], {x: 10, y: 10});
                        }

                      function closeDialog(id) {
                          if(!id){
                              id = "tooltipDialog";
                              map.setMapCursor("default");
                          }
                          var widget = dijit.byId(id);
                          if (widget) {
                              widget.destroy();
                          }
                      }

                      map.on("load", mapLoad);
                      map.on("click", mapClick);

                      function mapLoad() {
                          console.log("开始load");
                          initMapGrid();
                      }

                      function mapClick(e) {
                          console.log(e.mapPoint.x + "  -----   " + e.mapPoint.y);
                          if (!e.graphic)
                              map.infoWindow.hide();
                          else if (e.graphic.attributes && e.graphic.attributes["xzqhdm"]) {
                              _this.commonData.gridCode = e.graphic.attributes["xzqhdm"];
                              _this.getGridAreaAndData();
                          }
                      }
                      //以下本应该放在方法里

                      function initMapGrid() {
                        //          GIS_GRID           + 济南 2;槐荫区 3；居委会 4； 网格 5
                        var layer = _this.config.baseGridServerUrl + getNextLevelGridServerNameByDeptCode(_this.config.topDeptCode);
                        console.log(layer);
                        var baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
                        var appendParam = getAppendParamByDeptCode(_this.config.topDeptCode);
                        console.log(appendParam);
                        baseUrl += "&cql_filter=" + appendParam;
                          console.log(baseUrl);
                        $.ajax({
                            type: 'post',
                            url: baseUrl,
                            dataType: 'json',
                            success: success
                        });
                        function success(result) {
                            console.log(result);
                            gridGraphicsLayer.clear();
                            //textGraphicsLayer.clear();
                            if (!countyGridArray)
                                countyGridArray = result.features;
                            for (var i = 0; i < result.features.length; i++) {
                                var obj = result.features[i];
                                var polygonJson;
                                if (obj.geometry.type === "Polygon") {
                                    polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": 4326}};
                                } else {
                                    var geoArr = [];
                                    for (var n = 0; n < obj.geometry.coordinates.length; n++) {
                                        geoArr.push(obj.geometry.coordinates[n][0]);
                                    }
                                    polygonJson = {"rings": geoArr, "spatialReference": {"wkid": 4326}};
                                }
                                var polygon = new Polygon(polygonJson);
                                var gra = new Graphic(polygon, gridFillSymbol, obj.properties);
                                gridGraphicsLayer.add(gra);

                                //var font = new Font("15px", Font.STYLE_NORMAL, Font.VARIANT_NORMAL, Font.WEIGHT_NORMAL);
                                //var textSymbol = new TextSymbol(obj.properties["XZQHMC"], font, new Color([0, 33, 99]));
                                //var point = new Point(obj.properties.LNG, obj.properties.LAT, new esri.SpatialReference(4326));
                                //var labelPointGraphic = new Graphic(point, textSymbol);
                            }
                            map.setExtent(graphicsUtils.graphicsExtent(gridGraphicsLayer.graphics), true);
                            _this.getGridAreaAndData();
                        }
                    }
                   

                    
                   
              })
        },//init 结束
         getGridAreaAndData() {
            this.clearMap();
            this.getGridData();
            this.getCurrentGridGeom();
        },
        clearMap() {
            map.infoWindow.hide();
            gridGraphicsLayer.clear();
            currentGridPolygon = "";
        },

        getGridData() {
            this.getGridListByAttribute(this.commonData.gridCode);
        },
        getCurrentGridGeom() {
            console.log("获取code=="+this.commonData.gridCode);
            var layer = this.config.baseGridServerUrl + getGridServerNameByDeptCode(this.commonData.gridCode);
            var baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
            if (getGridLevelByDeptCode(this.commonData.gridCode) !== "1") {
                var appendParam = "xzqhdm=" + this.commonData.gridCode;
                baseUrl += "&cql_filter=" + appendParam;
            }
            $.ajax({
                type: 'post',
                url: baseUrl,
                dataType: 'json',
                success: this.gotCurrentGridGeomResult
            });
        },
        gotCurrentGridGeomResult(result) {
            if (result && result.features.length >= 1) {
                var obj = result.features[0];
                var polygonStr = "";
                if("MultiPolygon" === obj.geometry.type){
                    for (var i = 0; i < obj.geometry.coordinates[0][0].length; i++) {
                        polygonStr += obj.geometry.coordinates[0][0][i][0] + "," + obj.geometry.coordinates[0][0][i][1] + " "
                    }
                }else{
                    for (var j = 0; j < obj.geometry.coordinates[0].length; j++) {
                        polygonStr += obj.geometry.coordinates[0][j][0] + "," + obj.geometry.coordinates[0][j][1] + " "
                    }
                }
                currentGridPolygon = polygonStr;
                console.log(currentGridPolygon);
            }else if(getGridLevelByDeptCode(this.commonData.gridCode) !== "0"){
                // $.modal.alertWarning("此区域未划分网格。");
                console.log("此区域未划分网格。");

            }
        },

                    /*****************************各模块公用查询方法结束*****************************/
        //定义一个获取数据
         /*****************************地图网格范围查询开始*****************************/
                    // 属性查询
                    getGridListByAttribute(gridCode) {
                         loadModules([
                            'esri/geometry/Polygon',
                            'esri/graphic',
                            'esri/graphicsUtils'
                        ], { css: true })
                        .then(([Polygon,Graphic, graphicsUtils]) => {             
                            let _this = this;   
                        var layer = _this.config.baseGridServerUrl + getNextLevelGridServerNameByDeptCode(gridCode);
                        var appendParam = getAppendParamByDeptCode(gridCode);
                        var baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
                        baseUrl += "&cql_filter=" + appendParam;
                        $.ajax({
                            type: 'post',
                            url: baseUrl,
                            dataType: 'json',
                            success: getGridListResult
                        });
                            function getGridListResult(result) {
                                gridGraphicsLayer.clear();
                                //textGraphicsLayer.clear();
                                // if (!countyGridArray)
                                    countyGridArray = result.features;
                                if(result.features.length === 0){
                                    // $.modal.alertWarning("此区域未划分网格。");
                                }else{
                                    for (var i = 0; i < result.features.length; i++) {
                                        var obj = result.features[i];
                                        var polygonJson;
                                        if (obj.geometry.type === "Polygon") {
                                            polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": 4326}};
                                        } else {
                                            var geoArr = [];
                                            for (var n = 0; n < obj.geometry.coordinates.length; n++) {
                                                geoArr.push(obj.geometry.coordinates[n][0]);
                                            }
                                            polygonJson = {"rings": geoArr, "spatialReference": {"wkid": 4326}};
                                        }
                                        var polygon = new Polygon(polygonJson);
                                        var gra = new Graphic(polygon, gridFillSymbol, obj.properties);
                                        gridGraphicsLayer.add(gra);
                                        //var font = new Font("15px", Font.STYLE_NORMAL, Font.VARIANT_NORMAL, Font.WEIGHT_NORMAL);
                                        //var textSymbol = new TextSymbol(obj.properties["XZQHMC"], font, new Color([0, 33, 99]));
                                        //var point = new Point(obj.properties.LNG, obj.properties.LAT, new SpatialReference(4326));
                                        //var labelPointGraphic = new Graphic(point, textSymbol);
                                        // textGraphicsLayer.add(labelPointGraphic);
                                    }
                                    map.setExtent(graphicsUtils.graphicsExtent(gridGraphicsLayer.graphics), true);
                                }
                                //getNextModuleData();
                            }
                        })
                    },
    },
  mounted() {
     
  },

  beforeDestroy() {
    if (this.view) {
      // destroy the map view
      this.view.container = null
    }
  },
}
</script>
 
<style lang="scss" scoped>

</style>